//
//  BluetoothObserver.m
//  Do Not Disturb
//
//  Created by Chris Karr on 8/28/07.
//  Copyright 2007 __MyCompanyName__. All rights reserved.
//

#import "BluetoothObserver.h"
#import <IOBluetooth/objc/IOBluetoothDevice.h>
#import "DNDDefines.h"

@implementation BluetoothObserver

- (BluetoothObserver *) init
{
	if (self = [super init])
	{
		search = nil;
		searching = NO;
	}
	
	return self;
}

- (void) start
{
	BluetoothHCIVersionInfo * bluetooth = malloc (sizeof (bluetooth));
	NumVersion version;

	IOBluetoothGetVersion (&version, bluetooth);
	
	if (bluetooth->hciVersion)
	{
		searching = YES;

		if (search != nil)
		{
			[search clearFoundDevices];
			[search release];
		}
		
		search = [[IOBluetoothDeviceInquiry inquiryWithDelegate:self] retain];
		[search setUpdateNewDeviceNames:YES];
		[search setSearchCriteria:kBluetoothServiceClassMajorAny majorDeviceClass:kBluetoothDeviceClassMajorAny
					minorDeviceClass:kBluetoothDeviceClassMinorAny]; 

		
		[search start];
	}
	else
	{
		searching = NO;
		return;
	}
}

- (void) scan
{
	if (!searching)
		[self start];
}

- (void) deviceInquiryDeviceNameUpdated:(IOBluetoothDeviceInquiry*)sender 
        device:(IOBluetoothDevice*)device devicesRemaining:(uint32_t)devicesRemaining
{
	NSLog (@"device = %@", [device getNameOrAddress]);
	NSLog (@"%d devices left", devicesRemaining);
}
		
- (void) deviceInquiryComplete:(IOBluetoothDeviceInquiry *) sender error:(IOReturn) error aborted:(BOOL)aborted
{
	NSArray * devices = [sender foundDevices];
	
	int i = 0;
	for (i = 0; i < [devices count]; i++)
	{
		IOBluetoothDevice * device = [devices objectAtIndex:i];

		NSMutableDictionary * dict = [NSMutableDictionary dictionary];
		[dict setValue:[NSDate date] forKey:@"date"];
		[dict setValue:[NSString stringWithFormat:@"Found Bluetooth Device: %@", [device getNameOrAddress]] forKey:@"name"];
			// [dict setValue:device forKey:@"object"];
	
		[[NSDistributedNotificationCenter defaultCenter] postNotificationName:DND_UPDATE object:@"BluetoothObserver" userInfo:dict];
	}

	searching = NO;
}

- (void) deviceInquiryStarted: (IOBluetoothDeviceInquiry *) sender
{

}

- (NSString *) getName
{
	return @"Bluetooth";
}

@end
